import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { NavBar, Form, Field, Button, CountDown, Toast } from 'react-vant'
import styles from './index.module.css';
import { sendSms, login } from '../../api/user'
import { setToken } from '../../utils'
export default () => {
    const navigate = useNavigate()
    const [tel, setTel] = useState(13911111111)
    const [code, setCode] = useState(246810)
    const [time, setTime] = useState(false)
    const onClickCode = async () => {
        try {
            setTime(true)
            const res = await sendSms(tel)
            Toast.success('发送成功')
        } catch (error) {
            Toast('发送太频繁，请稍后再试')
        }
    }
    const onLogin = async () => {
        try {
            Toast.loading({
                message: '加载中...',
                forbidClick: true,
                duration: 0
            });
            const res = await login({
                mobile: tel.toString(),
                code: code.toString()
            })
            setToken(res.data.data.token)
            Toast.success("登录成功")
            navigate('/my')
        } catch (error) {
            Toast('验证码不正确')
        }
    }
    return (<div>
        <NavBar
            title="登录"
            leftArrow
            onClickLeft={() => navigate('/my')}
        />
        <div className={styles.lin}>
            <Field label={'手机号'} placeholder="请输入手机号" maxlength={11} value={tel} onChange={setTel} />
            <Field
                value={code}
                center
                clearable
                label="短信验证码"
                placeholder="请输入短信验证码"
                onChange={setCode}
                button={time ?
                    <Button size="small" round type="default" > <CountDown
                        time={5 * 1000}
                        format="ss秒"
                        onFinish={() => { setTime(false) }}
                    /></Button> : <Button onClick={onClickCode} round size="small" type="default" text="发送验证码" />}
            />
            <Button type="primary" block onClick={onLogin}>
                登录
            </Button>
        </div>

    </div >)
}